import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FormlyFieldConfig, FormlyFormOptions } from '@ngx-formly/core';
import { ApiService } from '@core/services/http/api.service';
import { dateFormat } from '../../../../../utils/utils';
import { BiService } from '../../../bi.service';

@Component({
  selector: 'customer-complaint',
  templateUrl: './customer-complaint.component.html',
  // styleUrls: ['./customer-complaint.component.scss'],
})
export class CustomerComplaintComponent implements OnInit {

  // 客诉分析

  // 客诉处理效率
  // 效率
  efficiencyOption: any = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
    },
    legend: {
      data: ['单量', '已处理', '时效'],
    },
    xAxis: {
      type: 'category',
    },
    yAxis: [
      {
        name: '单量',
        type: 'value',
        axisLabel: {
          formatter: '{value} 单',
        },
      },
      {
        name: '耗时',
        type: 'value',
        axisLabel: {
          formatter: '{value} 分钟',
        },
      },
    ],
    series: [
      { name: '单量', type: 'bar', label: { show: true } },
      { name: '已处理', type: 'bar', label: { show: true } },
      { name: '时效', type: 'line', yAxisIndex: 1 },
    ],
  };
  efficiencyField: FormlyFieldConfig[] = [
    {
      key: 'DEPT_ID',
      type: 'conditionInput',
      templateOptions: {
        label: '所属门店',
        config: {
          api: 'cm.dept.findAll',
          init: true,
          operators: ['EQ'],
          type: 'select',
          downFormatter: 'value.name',
          multiple: true,
          valueFormatter: 'value.name',
          searchFormId: 'cm.dept.findAllWithAccessProvider',
          rowSelection: 'multiple',
          addSame: false,
          uniqueKey: 'id',
        },
        domain: '{"filters":[{"field":"id","operator":"LIKE","value":"{{value}}"},{"field":"name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}',
        divCol: 5,
      },
    },
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'monthRange',
        },
        divCol: 5,
      },
    },
  ];
  efficiencyData: any;
  efficiencyModel: any = {};
  efficiencyLoading: boolean = false;

  // 员工
  staffField: FormlyFieldConfig[] = [
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'month',
        },
        divCol: 5,
      },
    },
  ];
  staffData: any;
  staffModel: any = {};
  staffLoading: boolean = false;

  // 数量
  quantityOption: any = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
    },
    legend: {
      data: ['平均耗时', '停单中', '已结单', '处理中'],
    },
    xAxis: {
      type: 'category',
    },
    yAxis: [
      {
        name: '单量',
        type: 'value',
        axisLabel: {
          formatter: '{value} 单',
        },
      },
      {
        name: '耗时',
        type: 'value',
        axisLabel: {
          formatter: '{value} 分钟',
        },
      },
    ],
    series: [
      { name: '停单中', type: 'bar', stack: '客诉单', emphasis: { focus: 'series' }, label: { show: true } },
      { name: '已结单', type: 'bar', stack: '客诉单', emphasis: { focus: 'series' }, label: { show: true } },
      { name: '处理中', type: 'bar', stack: '客诉单', emphasis: { focus: 'series' }, label: { show: true } },
      { name: '平均耗时', type: 'line', yAxisIndex: 1 },
    ],
  };
  quantityField: FormlyFieldConfig[] = [
    {
      key: 'DEPT_ID',
      type: 'conditionInput',
      templateOptions: {
        label: '所属门店',
        config: {
          api: 'cm.dept.findAll',
          init: true,
          operators: ['EQ'],
          type: 'select',
          downFormatter: 'value.name',
          multiple: true,
          valueFormatter: 'value.name',
          searchFormId: 'cm.dept.findAllWithAccessProvider',
          rowSelection: 'multiple',
          addSame: false,
          uniqueKey: 'id',
        },
        domain: '{"filters":[{"field":"id","operator":"LIKE","value":"{{value}}"},{"field":"name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}',
        divCol: 5,
      },
    },
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'monthRange',
        },
        divCol: 5,
      },
    },
  ];
  quantityData: any;
  quantityModel: any = {};
  quantityLoading: boolean = false;

  // 结单客诉满意率
  satisfactionOption: any = {
    tooltip: {
      trigger: 'item',
      formatter: this.showSatisfactionTooltip,
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      // data: ['非常满意', '满意', '不满意', '一般', '非常不满意'],
    },
    series: [
      {
        name: '满意率', type: 'pie', radius: '50%', emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };
  satisfactionField: FormlyFieldConfig[] = [
    {
      key: 'DEPT_ID',
      type: 'conditionInput',
      templateOptions: {
        label: '所属门店',
        config: {
          api: 'cm.dept.findAll',
          init: true,
          operators: ['EQ'],
          type: 'select',
          downFormatter: 'value.name',
          multiple: true,
          valueFormatter: 'value.name',
          searchFormId: 'cm.dept.findAllWithAccessProvider',
          rowSelection: 'multiple',
          addSame: false,
          uniqueKey: 'id',
        },
        domain: '{"filters":[{"field":"id","operator":"LIKE","value":"{{value}}"},{"field":"name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}',
        divCol: 5,
      },
    },
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'month',
        },
        divCol: 5,
      },
    },
  ];
  satisfactionData: any;
  satisfactionModel: any = {};
  satisfactionLoading: boolean = false;
  satisfactionGirdData: any = [];


  // 客诉率
  complaintOption: any = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
    },
    legend: {
      data: ['单量', '车流', '客诉率'],
    },
    xAxis: {
      type: 'category',
    },
    yAxis: [
      {
        name: '数量',
        type: 'value',
      },
      {
        name: '客诉率',
        type: 'value',
        axisLabel: {
          formatter: '{value} %',
        },
      },
    ],
    series: [
      { name: '单量', type: 'bar', label: { show: true } },
      { name: '车流', type: 'bar', label: { show: true } },
      { name: '客诉率', type: 'line', yAxisIndex: 1 },
    ],
  };
  complaintField: FormlyFieldConfig[] = [
    {
      key: 'DEPT_ID',
      type: 'conditionInput',
      templateOptions: {
        label: '所属门店',
        config: {
          api: 'cm.dept.findAll',
          init: true,
          operators: ['EQ'],
          type: 'select',
          downFormatter: 'value.name',
          multiple: true,
          valueFormatter: 'value.name',
          searchFormId: 'cm.dept.findAllWithAccessProvider',
          rowSelection: 'multiple',
          addSame: false,
          uniqueKey: 'id',
        },
        domain: '{"filters":[{"field":"id","operator":"LIKE","value":"{{value}}"},{"field":"name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}',
        divCol: 5,
      },
    },
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'monthRange',
        },
        divCol: 5,
      },
    },
  ];
  complaintData: any;
  complaintModel: any = {};
  complaintLoading: boolean = false;

  // 客诉类型、类别
  typesOfField: FormlyFieldConfig[] = [
    {
      key: 'DEPT_ID',
      type: 'conditionInput',
      templateOptions: {
        label: '所属门店',
        config: {
          api: 'cm.dept.findAll',
          init: true,
          operators: ['EQ'],
          type: 'select',
          downFormatter: 'value.name',
          multiple: true,
          valueFormatter: 'value.name',
          searchFormId: 'cm.dept.findAllWithAccessProvider',
          rowSelection: 'multiple',
          addSame: false,
          uniqueKey: 'id',
        },
        domain: '{"filters":[{"field":"id","operator":"LIKE","value":"{{value}}"},{"field":"name","operator":"LIKE","value":"{{value}}"}],"groups":[],"operator":"or"}',
        divCol: 5,
      },
    },
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'month',
        },
        divCol: 5,
      },
    },
  ];
  typesOfCol: any[] = [];
  typesOfTotal: any = 0;
  typesOfData: any;
  typesOfModel: any = {};
  typesOfLoading: boolean = false;

  // 客诉排名
  // 排名
  rankOption: any = {
    title: {
      subtext: '客诉排序TOP20',
      left: 'left',
    },
    tooltip: {
      trigger: 'item',
      formatter: this.showRankTooltip,
    },
    xAxis: {
      type: 'value',
    },
    yAxis: {
      type: 'category',
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    series: [
      { name: '客诉单', type: 'bar', sort: 'none', label: { show: true } },
    ],

  };
  rankField: FormlyFieldConfig[] = [
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'month',
        },
        divCol: 5,
      },
    },
  ];
  rankData: any;
  rankModel: any = {};
  rankLoading: boolean = false;

  // 原因
  reasonOption: any = {
    title: {
      subtext: '客诉原因',
      left: 'left',
    },
    tooltip: {
      trigger: 'item',
      formatter: this.showRankTooltip,
    },
    xAxis: {
      type: 'value',
    },
    yAxis: {
      type: 'category',
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    series: [
      { name: '原因', type: 'bar', sort: 'none', label: { show: true } },
    ],
  };
  reasonData: any;
  reasonLoading: boolean = false;

  constructor(
    private apiService: ApiService,
    private bi: BiService,
  ) {

  }

  ngOnInit() {
    setTimeout(() => {
      this.refreshEfficiencyData();
      this.refreshStaffData();
      this.refreshQuantityData();
      this.refreshSatisfactionData();
      this.refreshComplaintData();
      this.refreshTypesOfData();
      this.refreshRankData();
    }, 1000);
  }

  showSatisfactionTooltip(params) {
    let tooltip = params.seriesName + '<br/>' + params.name + ' : ' + params.data[1] + ' (' + params.percent + '%)';
    return tooltip;
  }

  refreshEfficiencyData() {
    let date = this.bi.conversionMonths(this.efficiencyModel['DATE']);
    let id = this.efficiencyModel['DEPT_ID'] ? this.efficiencyModel['DEPT_ID'] : [];

    const data = {
      DEPT_ID: id,
      DATE_START: date[0],
      DATE_END: date[1],
    };

    let api = 'fn.customComplain.customPlainHandleEfficiencyDept';

    this.efficiencyLoading = true;
    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {
      // console.log('客诉处理效率', body);
      // let dimensions = [];
      let source = [['INITIAT_OA_DATE','TOTAL','HANDLED','AVERAGE_HANDLED_CONSUME']];
      if (body && body.length != 0) {
        body.forEach((res) => {
          // dimensions.push(res['INITIAT_OA_DATE']);
          source.push([
            res['INITIAT_OA_DATE'],
            res['TOTAL'],
            res['HANDLED'],
            res['AVERAGE_HANDLED_CONSUME'],
          ]);

        });
      }
      this.efficiencyData = {
        dataset: {
          // dimensions: dimensions,
          source: source,
        },
      };
      this.efficiencyLoading = false;
    });
  }

  refreshStaffData() {
    let date = this.bi.conversionMonth(this.staffModel['DATE']);

    let nowDate = this.bi.currentMonths(date);

    const data = {
      DATE_END: date,
    };

    let api = 'fn.customComplain.customPlainHandleEfficiencyPerson';

    this.staffLoading = true;
    this.staffData = [];
    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {
        // console.log('员工客诉处理', body);
        if (body && body.length != 0) {
          let thisMonth: any[] = [];
          let firstMonth: any[] = [];
          body.forEach((res) => {
            if (res.CREATE_DATE == nowDate) {
              thisMonth.push(res);
            } else {
              firstMonth.push(res);
            }
          });
          if (thisMonth.length != 0 && firstMonth.length != 0) {
            thisMonth.forEach((tMonth) => {
              firstMonth.forEach((fMonth) => {
                if (fMonth.OPERATOR_NAME == tMonth.OPERATOR_NAME) {
                  tMonth['OLD_TASK'] = fMonth.TASK;
                  tMonth['OLD_AVERAGE_CONSUME'] = fMonth.AVERAGE_CONSUME;
                }
              });
            });
          }
          this.staffData = thisMonth;
        }
        this.staffLoading = false;
      },
    );
  }

  showStaffText(oldT, newT, type = false) {
    let showText = '--';
    if (oldT && oldT != '--') {
      let t;
      if (oldT > newT) {
        t = oldT - newT;
      } else if (oldT < newT) {
        t = newT - oldT;
      } else {
        t = '--';
      }
      if (type && t != '--') {
        showText = t.toFixed(2);
      } else {
        showText = t;
      }
    }
    return showText;
  }

  showStaffClass(oldT, newT) {
    let showClass = 'noChange';
    if (oldT && oldT != '--') {
      if (oldT > newT) {
        showClass = 'showDown';
      } else if (oldT < newT) {
        showClass = 'showUp';
      } else {
        showClass = 'noChange';
      }
    }
    return showClass;
  }

  refreshQuantityData() {
    let date = this.bi.conversionMonths(this.quantityModel['DATE']);
    let id = this.quantityModel['DEPT_ID'] ? this.quantityModel['DEPT_ID'] : [];

    const data = {
      DEPT_ID: id,
      DATE_START: date[0],
      DATE_END: date[1],
    };

    let api = 'fn.customComplain.customPlainCountAndConsume';

    this.quantityLoading = true;

    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {
        // console.log('客诉处理数量', body);
        // let dimensions = [];
        let source = [['INITIAT_OA_DATE','STOP_NUM','END_NUM','DISPOSE_NUM','AVERAGE_CONSUME']];
        if (body && body.length != 0) {
          body.forEach((res) => {
            // dimensions.push(res['INITIAT_OA_DATE']);
            source.push([
              res['INITIAT_OA_DATE'],
              res['STOP_NUM'],
              res['END_NUM'],
              res['DISPOSE_NUM'],
              res['AVERAGE_CONSUME'],
            ]);

          });
        }
        this.quantityData = {
          dataset: {
            // dimensions: dimensions,
            source: source,
          },
        };
        this.quantityLoading = false;
      },
    );

    // this.quantityData = {
    //   dataset: {
    //     dimensions: ['2020.09', '2020.10', '2020.11', '2020.12'],
    //     source: [
    //       ['2020.09', 10, 20, 30, 5],
    //       ['2020.10', 20, 10, 40, 3],
    //       ['2020.11', 20, 30, 50, 2],
    //       ['2020.12', 10, 10, 40, 7],
    //     ],
    //   },
    // };
    // this.quantityLoading = false;
  }

  refreshSatisfactionData() {
    let date = this.bi.conversionMonth(this.satisfactionModel['DATE']);
    let id = this.satisfactionModel['DEPT_ID'] ? this.satisfactionModel['DEPT_ID'] : [];

    let nowDate = this.bi.currentMonths(date);

    const data = {
      DEPT_ID: id,
      DATE_END: date,
    };

    let api = 'fn.customComplain.customPlainSatisfaction';

    this.satisfactionLoading = true;
    this.satisfactionGirdData = [];

    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {
        // console.log(testData);
        // console.log('结单客诉满意率', body);
        let source = [];
        if (body && body.length != 0) {
          let res = body[1] ? body[1] : body[0];
          source.push(['非常满意', res['VERY_SATISFY_NUM']]);
          source.push(['满意', res['SATISFY_NUM']]);
          source.push(['一般', res['COMMON_NUM']]);
          source.push(['不满意', res['UNSATISFY_NUM']]);
          source.push(['非常不满意', res['VERY_UNSATISFY_NUM']]);

          let thisMonth: any;
          let firstMonth: any;
          let showData: any[] = [];

          if (res.INITIAT_OA_DATE == nowDate && body.length > 1) {
            thisMonth = body[1];
            firstMonth = body[0];
          } else {
            thisMonth = body[0];
          }

          let tTotal = 0;
          let fTotal = 0;
          for (let tKey in thisMonth) {
            if (typeof thisMonth[tKey] == 'number') {
              tTotal += thisMonth[tKey];
            }
          }

          if (firstMonth) {
            for (let tKey in firstMonth) {
              if (typeof firstMonth[tKey] == 'number') {
                fTotal += firstMonth[tKey];
              }
            }
          }

          for (let tKey in thisMonth) {
            let tMonth = (thisMonth[tKey] / tTotal * 100).toFixed(2);
            let fMonth: any = '--';
            if (firstMonth) {
              fMonth = firstMonth[tKey] / fTotal * 100;
            }

            switch (tKey) {
              case 'VERY_SATISFY_NUM':
                showData.push({ name: '非常满意', tMonth: tMonth, fMonth: fMonth });
                break;
              case 'SATISFY_NUM':
                showData.push({ name: '满意', tMonth: tMonth, fMonth: fMonth });
                break;
              case 'COMMON_NUM':
                showData.push({ name: '一般', tMonth: tMonth, fMonth: fMonth });
                break;
              case 'UNSATISFY_NUM':
                showData.push({ name: '不满意', tMonth: tMonth, fMonth: fMonth });
                break;
              case 'VERY_UNSATISFY_NUM':
                showData.push({ name: '非常不满意', tMonth: tMonth, fMonth: fMonth });
                break;
              default:
                break;
            }
          }

          this.satisfactionGirdData = showData;
        }
        this.satisfactionData = {
          dataset: {
            dimensions: ['满意率', '非常满意', '满意', '不满意', '一般', '非常不满意'],
            source: source,
          },
        };
        this.satisfactionLoading = false;
      },
    );

    // this.satisfactionData = {
    //   dataset: {
    //     dimensions: ['满意率', '非常满意', '满意', '不满意', '一般', '非常不满意'],
    //     source: [
    //       ['非常满意', 15],
    //       ['满意', 10],
    //       ['不满意', 20],
    //       ['一般', 30],
    //       ['非常不满意', 5],
    //     ],
    //   },
    // };
    // this.satisfactionLoading = false;
  }

  refreshComplaintData() {
    let date = this.bi.conversionMonths(this.complaintModel['DATE']);
    let id = this.complaintModel['DEPT_ID'] ? this.complaintModel['DEPT_ID'] : [];

    const data = {
      DEPT_ID: id,
      DATE_START: date[0],
      DATE_END: date[1],
    };

    let api = 'fn.customComplain.customPlainRate';

    this.complaintLoading = true;
    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {
      // console.log('客诉率', body);
      let dimensions = [];
      let source = [];
      if (body && body.length != 0) {
        body.forEach((res) => {
          let complaintRate = res['COMPLAIN_NUM'] / res['CAR_NUMBER'];
          dimensions.push(res['INITIAT_OA_DATE']);
          source.push([
            res['CREATE_DATE'],
            res['COMPLAIN_NUM'],
            res['CAR_NUMBER'],
            complaintRate.toFixed(2),
          ]);

        });
      }
      this.complaintData = {
        dataset: {
          dimensions: dimensions,
          source: source,
        },
      };
      this.complaintLoading = false;
    });
  }

  refreshTypesOfData() {
    let date = this.bi.conversionMonth(this.typesOfModel['DATE']);
    let id = this.typesOfModel['DEPT_ID'] ? this.typesOfModel['DEPT_ID'] : [];

    const data = {
      DEPT_ID: id,
      DATE_END: date,
    };
    let nowDate = this.bi.currentMonths(date);

    let api = 'fn.customComplain.customPlainType';

    this.typesOfLoading = true;
    this.typesOfCol = [];
    this.typesOfData = [];
    this.typesOfTotal = 0;

    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {
        // console.log('客诉类别/类型', body);
        if (body && body.length != 0) {
          let thisMonth: any[] = [];
          let firstMonth: any[] = [];
          body.forEach((res) => {
            if (res.INITIAT_OA_DATE == nowDate) {
              thisMonth.push(res);
            } else {
              firstMonth.push(res);
            }
          });
          let tColData = this.filterName(thisMonth, firstMonth, 'COMPLAIN_TYPE_NAME');
          let tRowData = this.filterName(thisMonth, firstMonth, 'COMPLAIN_CATEGORY_NAME');
          // let fColData = this.filterName(firstMonth, 'COMPLAIN_TYPE_NAME');
          // let fRowData = this.filterName(firstMonth, 'COMPLAIN_CATEGORY_NAME');

          let total = 0;
          tColData.forEach((col) => {
            total += col.total;
          });

          tRowData.forEach((row) => {
            tColData.forEach((col) => {
              let rowKey = row.name;
              let colKey = col.name;
              row[colKey] = this.filterData(thisMonth, rowKey, colKey);
            });
          });

          if (tRowData.length != 0) {
            tRowData.push(this.filterTotalData(tColData, '合计'));
            tRowData.push(this.filterTotalData(tColData, '占比'));
            // tRowData.push(this.filterTotalData(tColData, '客诉率'));
          }

          // console.log('colData', tColData);
          // console.log('rowData', tRowData);
          this.typesOfTotal = total;
          this.typesOfCol = tColData;
          this.typesOfData = tRowData;
        }
        this.typesOfLoading = false;
      },
    );
  }

  filterName(dataItem, oldDataItem, key) {
    let colData = [];

    dataItem.forEach((data) => {
      let colPush = true;

      colData.forEach((col) => {
        if (data[key] == col.name) {
          colPush = false;
        }
      });
      if (colData.length == 0 || colPush) {
        colData.push({ name: data[key] });
      }
    });

    colData.forEach((col) => {

      let total = 0;
      dataItem.forEach((data) => {
        if (data[key] == col.name) {
          total += data.NUM;
        }
      });
      col['total'] = total;

      let oldTotal = 0;
      oldDataItem.forEach((data) => {
        if (data[key] == col.name) {
          oldTotal += data.NUM;
        }
      });
      col['oldTotal'] = oldTotal;

    });

    return colData;
  }

  filterData(dataItem, rowKey, colKey) {
    let num = 0;

    dataItem.forEach((data) => {
      if (data['COMPLAIN_CATEGORY_NAME'] == rowKey && data['COMPLAIN_TYPE_NAME'] == colKey) {
        num = data.NUM;
      }
    });
    return num;
  }

  filterTotalData(dataItem, name: string) {
    let obj = { name: name };
    let total = 0;
    dataItem.forEach((data) => {
      if (name != '占比' && name != '客诉率') {
        obj[data.name] = data.total;
        total += data.total;
      } else {
        obj[data.name] = 0;
      }
    });
    obj['total'] = total;

    return obj;
  }

  showRowPercentageData(data, col, name) {
    let num = data[name];
    let colNmu = col.total;
    let rowName = data.name;
    let show = '';
    let text;
    if (rowName == '占比') {
      text = colNmu / this.typesOfTotal * 100;
      show = (text).toFixed(2) + '%';
    } else if (rowName == '客诉率') {
      let t;
      // console.log(data);
    } else {
      if (num != 0) {
        show = num;
      }
    }
    return show;
  }

  showColPercentageData(data) {
    let num = data.total;
    let show = '';
    if (num != 0) {
      let text = num / this.typesOfTotal * 100;
      show = (text).toFixed(2) + '%';
    }
    return show;
  }

  refreshRankData() {
    let date = this.bi.conversionMonth(this.rankModel['DATE']);

    const data = {
      DATE_END: date,
    };

    let rankApi = 'fn.customComplain.customPlainCountRank';

    this.rankLoading = true;
    this.apiService.post(rankApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
        // console.log('客诉排名', body);
        // let dimensions = [];
        let source = [['DEPT_NAME','CUR_COMPLAIN_NUM','PREV_COMPLAIN_NUM']];
        if (body && body.length != 0) {
          for (let i = body.length - 1; i >= 0; i--) {
            let res = body[i];
            // dimensions.push(res['DEPT_NAME']);
            source.push([
              res['DEPT_NAME'],
              res['CUR_COMPLAIN_NUM'],
              res['PREV_COMPLAIN_NUM'],
            ]);
          }
        }
        this.rankData = {
          dataset: {
            // dimensions: dimensions,
            source: source,
          },
        };
        this.rankLoading = false;
      },
    );

    let reasonApi = 'fn.customComplain.customPlainReasonRank';

    this.reasonLoading = true;
    this.apiService.post(reasonApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
        // console.log('客诉原因', body);
        // let dimensions = [];
        let source = [['COMPLAIN_CATEGORY_NAME','CUR_COMPLAIN_NUM','PREV_COMPLAIN_NUM']];
        if (body && body.length != 0) {
          for (let i = body.length - 1; i >= 0; i--) {
            let res = body[i];
            // dimensions.push(res['COMPLAIN_CATEGORY_NAME']);
            source.push([
              res['COMPLAIN_CATEGORY_NAME'],
              res['CUR_COMPLAIN_NUM'],
              res['PREV_COMPLAIN_NUM'],
            ]);
          }
        }
        this.reasonData = {
          dataset: {
            // dimensions: dimensions,
            source: source,
          },
        };
        this.reasonLoading = false;
      },
    );

  }

  showRankTooltip(params) {
    let showText = '--';
    let oldT = params.data[2];
    if (params.data[2]) {
      let newT = params.data[1];
      let t;
      let type = 'noChange';
      if (oldT > newT) {
        t = oldT - newT;
        type = 'showDown';
      } else {
        t = newT - oldT;
        type = 'showUp';
      }
      if (t == 0 || type == 'noChange') {
        showText = '较上个月 持平';
      } else if (type == 'showUp') {
        showText = '较上个月 ↑' + t + '单';
      } else if (type == 'showDown') {
        showText = '较上个月 ↓' + t + '单';
      }
    }
    let tooltip = params.seriesName + '<br/>' + params.name + ' : ' + params.data[1] + ' ( ' + showText + ' )';
    return tooltip;
  }

}

